package com.simpletour.qa.service.service;

import com.simpletour.qa.service.entity.QuestionLike;
import com.simpletour.qa.service.entity.QuestionLikeCount;
import com.simpletour.qa.service.repository.QuestionLikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;


@Service
public class QuestionLikeService {

    @Autowired
    private QuestionLikeRepository questionLikeRepository;

    @Transactional
    public QuestionLikeCount save(QuestionLike questionLike){
        QuestionLikeCount questionLikeCountInfo = getQuestionLikeCountInfo(questionLike.getUserId(), questionLike.getQuestionId());
        if(!questionLikeCountInfo.isLike()){
            questionLike.setCreateTime(LocalDateTime.now());
            questionLikeRepository.save(questionLike);
        }
        return getQuestionLikeCountInfo(questionLike.getUserId(),questionLike.getQuestionId());
    }

    @Transactional
    public QuestionLikeCount deleteByUserIdAndQuestionId(int userId,int questionId){
        questionLikeRepository.deleteByUserIdAndQuestionId(userId,questionId);
        return getQuestionLikeCountInfo(userId,questionId);

    }

    public int findCountByQuestionId(int questionId){
        return questionLikeRepository.findCountByQuestionId(questionId);
    }

    public boolean isLikeByUserIdAndQuestionId(int userId,int questionId){
        if(questionLikeRepository.findCountByUserIdAndQuestionId(userId,questionId) == 0){
            return false;
        }
        return true;
    }

    @Transactional
    public QuestionLikeCount update(QuestionLike questionLike){
        if(isLikeByUserIdAndQuestionId(questionLike.getUserId(),questionLike.getQuestionId())){
            return deleteByUserIdAndQuestionId(questionLike.getUserId(),questionLike.getQuestionId());
        }else {
            return save(questionLike);
        }
    }



    /**
     * 获取点赞统计信息
     * @param userId
     * @param questionId
     * @return
     */
    public QuestionLikeCount getQuestionLikeCountInfo(int userId,int questionId){
        QuestionLikeCount questionLikeCount = new QuestionLikeCount();
        questionLikeCount.setQuestionId(questionId);
        questionLikeCount.setLike(isLikeByUserIdAndQuestionId(userId,questionId));
        questionLikeCount.setLikeNum(findCountByQuestionId(questionId));
        return questionLikeCount;
    }

}
